﻿using HAF.Dispatcher.Enum;
using HAF.Dispatcher.WorkItem;
using HAF.LogUtility.Assistantor;
using Iptv.MediaReporter.Entity;
using Iptv.MediaReporter.Helper;
using Iptv.MediaReporter.Model;
using RDS.Core;
using System;
using System.IO;
using System.Threading;

namespace Iptv.MediaReporter.SubItems
{
    /// <summary>
    /// 指纹采集任务
    /// </summary>
    public class MediaFingerItem : BaseWorkerItem, IDisposable
    {
        private LoadConfig _runConfig;
        public void Dispose()
        {
            WriteDebugMessage("指纹采集任务结束");
        }

        private void RefreshConfig()
        {
            //获取本地配置文件 每次执行的时候读取，实现热配置
            string loadConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, RuntimeAdapter.PluginDir, "ReportConfig.json");
            ShowDebugMessage("获取本地配置文件{0}", loadConfigPath);
            _runConfig = JsonAssistant.FromFile<LoadConfig>(loadConfigPath);
        }

        public override void ExecItem()
        {
            base.ExecItem();
            RefreshConfig();

            if (WorkItems != null && WorkItems is MediaEntity)
            {
                MediaEntity program = WorkItems as MediaEntity;
                PushFingerTask(program);
            }
            else
            {
                this.Statu = HAF.Dispatcher.Enum.EnumRunItemStatu.End;
            }
        }

        bool isWatch = true;
        /// <summary>
        /// 执行指纹采集任务
        /// </summary>
        /// <param name="taskinfo"></param>
        private void PushFingerTask(MediaEntity taskinfo)
        {
            try
            {
                ShowDebugMessageExt(taskinfo.MediaID, "当前任务远程地址为{0} 本地根目录地址为{1} ", taskinfo.RemoteFullPath, _runConfig.FingerPrintMediaPath);

                string localRealPath = taskinfo.RemoteFullPath.Replace(_runConfig.FingerPrintUrlPrefix, _runConfig.FingerPrintMediaPath);
                ShowDebugMessageExt(taskinfo.MediaID, "当前任务本地全路径地址为{0} ", localRealPath);

                var reportData = new FingerPrintData();
                reportData.vlist.Add(new ReportMediaUrlData()
                {
                    guid = taskinfo.MediaID,
                    videoUrl = localRealPath
                });
                string postData = JsonAssistant.Serialize(reportData);
                ShowDebugMessage(postData);
                string responseStr = WebHelper.GetHttpResponse(_runConfig.FingerPrintApiUrl, "Post", "application/json", postData);
                ShowDebugMessage(responseStr);
                var resModel = JsonAssistant.Deserialize<FingerPrintResponse>(responseStr);
                if (resModel != null)
                {
                    //提取返回的工作项编号
                    ShowDebugMessage(resModel.data.jobId);
                    isWatch = true;

                    while (isWatch)
                    {
                        Thread watchThread = new Thread(delegate () { GetFingerPrintResult(taskinfo.MediaID, resModel.data.jobId); }) { Name = "watchDog", IsBackground = true };
                        watchThread.Start();

                        Thread.Sleep(3 * 60 * 1000);  //暂停3分钟后去取结果
                    }
                }
                ShowInfoMessage("指纹采集任务{0}完成", localRealPath);
            }
            catch (Exception ex)
            {
                EndProcess?.Invoke(taskinfo.MediaID, false);
                ShowErrMessageExt(taskinfo.MediaID, string.Format("方法{0}发生异常：{1}", System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString()));
            }
        }

        private void GetFingerPrintResult(string mId, string jobId)
        {
            using (WatchFingerPrintItem fpResult = new WatchFingerPrintItem())
            {
                fpResult.ID = int.Parse(TimeHelper.GetTimeStamp());
                fpResult.TaskID = Guid.NewGuid().ToString("N");
                fpResult.Name = "WatchDog";
                fpResult.Priority = 10;
                fpResult.Model = EnumItemModel.Multi;
                fpResult.RedoTimes = 0;
                fpResult.WorkID = mId;
                fpResult.WriteConsoleMessageEvent = RuntimeAdapter.ShowConsol;
                //WorkType = (int)SoapType.Host,
                fpResult.BeginTime = DateTime.Now.AddSeconds(40); //任务创建后40秒启动
                fpResult.WorkJson = jobId;
                fpResult.WorkItems = null;
                fpResult.Statu = EnumRunItemStatu.Begin;
                fpResult.CallBack = CallBack;
                fpResult.EndProcess = EndWatch;
                fpResult.ExecItem();
            }
        }

        private void EndWatch(string tid, bool state)
        {
            isWatch = false;
            EndProcess?.Invoke(tid, state);
        }
    }
}
